package com.easylinkin.linkappapi.facerecognition.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.facerecognition.entity.PersonnelIdentifier;
import com.easylinkin.linkappapi.facerecognition.service.PersonnelIdentifierService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 提供人员身份管理接口
 * */
@RestController
@RequestMapping("/personnel/identifier")
public class PersonnelIdentifierController {

    @Autowired
    private PersonnelIdentifierService personnelIdentifierService;

    @Resource
    LinkappUserContextProducer linkappUserContextProducer;

    @PostMapping("/page")
    public RestMessage getIdentifier(@RequestBody RequestModel<PersonnelIdentifier> requestModel) {
        if (requestModel.getPage() == null) {
            QueryWrapper<PersonnelIdentifier> qw = new QueryWrapper<>();
            qw.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
            qw.eq("deleted", false);
            return RestBuilders.successBuilder().data(personnelIdentifierService.list(qw)).build();
        }
        IPage<PersonnelIdentifier> record = personnelIdentifierService.queryPersonnelList(requestModel.getPage(), requestModel.getCustomQueryParams());
        return RestBuilders.successBuilder().data(record).build();
    }

    /**
     * 新建一个人员身份标识.
     *
     * 保证同一个租户下身份标识的唯一性
     * */
    @PostMapping
    public RestMessage createIdentifier(@Validated @RequestBody PersonnelIdentifier identifier) {

        PersonnelIdentifier id = personnelIdentifierService.queryWithIdentifierName(identifier.getIdentifier());
        if (id != null) {
            return RestBuilders.failureBuilder().message("人员身份已存在").build();
        }

        identifier.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        boolean success = personnelIdentifierService.save(identifier);
        if (!success) {
            return RestBuilders.failureBuilder().message("身份保存失败").build();
        }

        return RestBuilders.successBuilder().build();
    }

    @PutMapping
    public RestMessage updateIdentifier(@Valid @RequestBody PersonnelIdentifier identifier) {
        if (identifier.getId() == null) {
            return RestBuilders.failureBuilder().message("身份ID为空").build();
        }
        identifier.setUpdateTime(new Date());
        PersonnelIdentifier id = personnelIdentifierService.queryWithIdentifierName(identifier.getIdentifier());
        if (id != null && !id.getId().equals(identifier.getId())) {
            return RestBuilders.failureBuilder().message("人员身份已存在").build();
        }
        boolean success = personnelIdentifierService.updateById(identifier);
        if (!success) {
            return RestBuilders.failureBuilder().message("身份更新失败").build();
        }

        return RestBuilders.successBuilder().build();
    }

    @DeleteMapping("/{id}")
    public RestMessage deleteIdentifier(@PathVariable("id") Long id) {

        PersonnelIdentifier identifier = personnelIdentifierService.getById(id);
        if (identifier == null || !identifier.getTenantId().equalsIgnoreCase(linkappUserContextProducer.getCurrent().getTenantId())) {
            return RestBuilders.failureBuilder().message("无法删除该人员身份").build();
        }
        identifier.setDeleted(true);
        identifier.setUpdateTime(new Date());

        boolean success = personnelIdentifierService.updateById(identifier);
        if (!success) {
            return RestBuilders.failureBuilder().message("身份删除失败").build();
        }

        return RestBuilders.successBuilder().build();
    }

    @PostMapping("/batch/delete")
    public RestMessage batchDeleteCamera(@RequestParam("ids") String ids) {
        if (ids == null || ids.isEmpty()) {
            return RestBuilders.successBuilder().build();
        }

        List<String> identifierIds = Arrays.asList(ids.split(","));

        String currentTenantId = linkappUserContextProducer.getCurrent().getTenantId();
        List<Long> deniedIds = personnelIdentifierService.listByIds(identifierIds).stream()
                .filter(r -> !r.getTenantId().equalsIgnoreCase(currentTenantId))
                .mapToLong(PersonnelIdentifier::getId)
                .boxed()
                .collect(Collectors.toList());

        if (deniedIds.size() != 0) {
            return RestBuilders.failureBuilder().message("无权删除").data(deniedIds).build();
        }

        if (!personnelIdentifierService.removeByIds(identifierIds)) {
            return RestBuilders.successBuilder().message("批量删除人员身份失败").build();
        }

        return RestBuilders.successBuilder().build();
    }

}
